package com.spring_mysql_redis.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spring_mysql_redis.annotation.CurrentUser;
import com.spring_mysql_redis.annotation.UserLoginToken;
import com.spring_mysql_redis.entity.Users;
import com.spring_mysql_redis.model.ResultFormat;
import com.spring_mysql_redis.model.ResultFormatPaging;
import com.spring_mysql_redis.service.UsersService;
import com.spring_mysql_redis.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since 2020-05-02
 */
@Api(tags = "用户信息管理")
@RestController
@RequestMapping("/users")
public class UsersController {

    private Logger logger = LoggerFactory.getLogger(UsersController.class);


    @Autowired
    private UsersService usersService;

    @Autowired
    private RandomIdUtil randomIdUtil;

    @Autowired
    private FilesUtils filesUtils;
    /**
     * 分页全查询用户信息
     *
     * @return
     */
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "Integer", defaultValue = "1"),
            @ApiImplicitParam(name = "limit", value = "每页记录数", required = true, dataType = "Integer", defaultValue = "5")
    })

    /**
     * 全查询分类信息
     *
     * @return
     */
    @ApiOperation("查询用户信息接口")
    @GetMapping("/list")
    public ResultFormatPaging pgUsersList(Users users, @RequestParam("page") Integer page, @RequestParam("limit") Integer limit) {
        logger.info("-------------------进入用户查询controller层--------------------------");
        logger.info("users={}", users);
        IPage<Users> usersIPage = usersService.selectUsersList(users, page, limit);
        List<Users> usersList = usersIPage.getRecords();
        logger.info("usersList={}", usersList);
        return ResultPagingUtil.pagingSuccess(0, usersIPage.getTotal(), usersList);

    }

    /**
     * 模糊查询用户信息，排除重要信息
     *
     * @return
     */
    @ApiOperation("查询用户信息接口")
    @GetMapping("/select")
    public ResultFormatPaging selectUsers(Users users, @RequestParam("keyword") String keyword, @RequestParam("page") Integer page, @RequestParam("limit") Integer limit) {
        logger.info("-------------------进入用户查询controller层--------------------------");
        users.setNickname(keyword);
        users.setUuId(keyword);
        logger.info("users={}", users);
        IPage<Users> usersIPage = usersService.selectUsers(users, page, limit);
        List<Users> usersList = usersIPage.getRecords();
        logger.info("usersList={}", usersList);
        return ResultPagingUtil.pagingSuccess(0, usersIPage.getTotal(), usersList);

    }

    /**
     * 添加用户信息
     *
     * @param users
     * @return
     */
    @ApiOperation("添加用户信息接口")
    @PostMapping("/save")
    @ResponseBody
    public ResultFormat savePgSorts(@RequestBody Users users) {
        System.out.println(users);
        users.setCreateTime(TimeUtitl.dateTime());
        users.setUuId(String.valueOf(randomIdUtil.RandomId()));
        ResultFormat insert = usersService.saveUsers(users);

        if (insert.getCode() == 200) {
            logger.info("添加成功");
            return ResultUtil.success();
        }
        if (insert.getCode() == 101) {
            logger.info("用户名已存在");
            return ResultUtil.error(insert.getCode(), insert.getMsg());
        }

        return ResultUtil.error(100, "添加失败");
    }


    /**
     * 修改用户信息
     *
     * @param users
     * @return
     */
    @ApiOperation("修改用户信息接口")
    @PutMapping("/update")
    @ResponseBody
    public ResultFormat updatePgSorts(Users users) {

        users.getCreateTime();
        users.setUpdateTime(TimeUtitl.dateTime());

        Integer insert = usersService.updateUsers(users);

        if (insert == 101) {
            logger.info("用户名已存在");
            return ResultUtil.error(101, "用户名已经存在");
        }
        if (insert == 200) {
            logger.info("修改成功");
            return ResultUtil.success();
        }

        return ResultUtil.error(100, "修改失败");

    }

    @ApiOperation("修改用户头像接口")
    @PostMapping("/upIcon")
    @ResponseBody
    public ResultFormat upIconPgSorts(@RequestParam("file") MultipartFile file, @CurrentUser Users user) {
        String url = filesUtils.iconPgSorts(file);
        user.setIcon(url);
        user.setUpdateTime(TimeUtitl.dateTime());
        Integer insert = usersService.upUsers(user);
        if (insert == 200) {
            logger.info("修改成功");
            return ResultUtil.success(url);
        }
        return ResultUtil.error(100, "修改失败");
    }

    @ApiOperation("修改用户密码接口")
    @PostMapping("/upPassword")
    @ResponseBody
    public ResultFormat upMmPgSorts(@RequestBody Users userPwd, @CurrentUser Users user) {
        if (DigestUtils.md5Hex(userPwd.getUserName()).equals(user.getPassword())){
            user.setPassword(DigestUtils.md5Hex(userPwd.getPassword()));
            Integer insert = usersService.upUsers(user);
            if (insert == 200) {
                logger.info("修改成功");
                return ResultUtil.success();
            }
            return ResultUtil.error(100, "修改失败");
        }
        return ResultUtil.error(100, "修改失败");
    }

    /**
     * 删除用户
     *
     * @param users
     * @return
     */
    @ApiOperation("删除用户接口")
    @PutMapping("/delete")
    public ResultFormat deletePgSorts(Users users) {

        logger.info("users=={}", users);
        Integer flag = usersService.deleteUsersId(users.getId());
        if (flag == 200) {
            logger.info("修改成功");
            return ResultUtil.success();
        } else {
            logger.info("修改失败");
            return ResultUtil.error(100, "修改失败");
        }
    }


    /**
     * 批量删除用户信息
     * 状态为1 :已删除
     *
     * @param state
     * @param id
     * @return
     */
    @PutMapping("delBatchUsers")
    @ApiOperation(value = "批量删除用户信息")
    public ResultFormat delBatchLink(Integer state, @RequestParam(value = "id[]") Integer[] id) {
        logger.info("state={}", state);

        Users users = new Users();
        users.setState(1);
        boolean updateById = false;
        for (Integer integer : id) {
            users.setId(integer);
            updateById = usersService.updateById(users);
        }
        if (updateById) {
            return ResultUtil.success();
        }
        return ResultUtil.error(100, "修改失败");
    }

    /**
     * 修改用户状态
     *
     * @param users
     * @return
     */
    @ApiOperation("用户登录接口")
//    @RequestMapping("/login")
    @PostMapping("/login")
    public ResultFormat loginPgSorts(@RequestBody Users users) {
        System.out.println(users);
        logger.info("userName :: password"+users.getUserName()+users.getPassword());
        ResultFormat flag = usersService.selectLogin(users.getUserName() , users.getPassword());
        if (flag.getCode() == 200) {
            logger.info("登录成功");
            return flag;
        } else {
            logger.info("登录失败");
            return ResultUtil.error(100, "登录失败");
        }
    }
    @ApiOperation("用户是否登录验证token接口")
//    @RequestMapping("/login")
    @PostMapping("/token")
    @UserLoginToken
    public ResultFormat tokenPgSorts() {
        return ResultUtil.success();
    }
}
